const express = require("express");
const router = express.Router();

const config = require("../../config/config");
const ArticleCateModel = require("../../model/articleCateModel");
const ArticleModel = require("../../model/articleModel");
const mongoose = require("../../model/core");
const { getUnix } = require("../../model/tools");

router.get("/", async (req, res) => {
    let result = await ArticleCateModel.aggregate([{
        $lookup: {
            from: "article_cate",
            localField: "_id",
            foreignField: "pid",
            as: "items"
        }
    }, {
        $match: { pid:"0" }
    }]);
    res.render("admin/articleCate/index.html", { list: result });
})

router.get("/add", async (req, res) => {
    // 获取顶级分类
    const topCateList = await ArticleCateModel.find({ pid: "0" });
    res.render("admin/articleCate/add.html", { cateList: topCateList });
})

router.post("/doAdd", async (req, res) => {
    try {
        if(req.body.pid != 0) {
            req.body.pid = mongoose.Types.ObjectId(req.body.pid);
        }
        console.log(`Object.assign(req.body, { add_time: getUnix() })`, Object.assign(req.body, { add_time: getUnix() }));
        const result = new ArticleCateModel(Object.assign(req.body, { add_time: getUnix() }));
        await result.save();
        res.render("admin/public/success.html", {
            "redirectUrl": `/${config.adminPath}/articleCate`,
            "message": "增加数据成功"
        });
    } catch (error) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${config.adminPath}/articleCate`,
            "message": "增加数据失败"
        });
    }
})

router.get("/edit", async (req, res) => {
    // 获取要修改数据的id
    const id = req.query.id;
    const result = await ArticleCateModel.find({ "_id": id });

    // 获取顶级分类
    const topCateList = await ArticleCateModel.find({ pid: "0" });
    if(result.length > 0) {
        res.render("admin/articleCate/edit.html", {
            list: result[0],
            cateList: topCateList
        });
    } else {
        res.redirect(`/${config.adminPath}/articleCate`);
    }
})

router.post("/doEdit", async (req, res) => {
    try {
        if(req.body.pid != 0) {
            req.body.pid = mongoose.Types.ObjectId(req.body.pid);
        }
        await ArticleCateModel.updateOne({ _id: req.body.id }, req.body);
        res.render("admin/public/success.html", {
            "redirectUrl": `/${config.adminPath}/articleCate`,
            "message": "修改数据成功"
        });
    } catch (error) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${config.adminPath}/articleCate`,
            "message": "修改数据失败"
        });
    }
});

router.get("/delete", async (req, res) => {
    let id = req.query.id;
    try {
        let subResult = await ArticleCateModel.find({ pid: mongoose.Types.ObjectId(id) });
        if(subResult.length > 0) {
            res.render("admin/public/error.html", {
                "redirectUrl": `/${config.adminPath}/articleCate`,
                "message": "当前分类没法删除，请删除下面的子分类重试"
            });
        } else {
            const subArticleResult = await ArticleModel.find({ cid: mongoose.Types.ObjectId(id) });
            if (subArticleResult.length > 0) {
                res.render("admin/public/error.html", {
                    "redirectUrl": `/${config.adminPath}/articleCate`,
                    "message": "当前分类下面有文章没法删除，请删除文章后重试"
                });
            } else {
                await ArticleCateModel.deleteOne({ _id: mongoose.Types.ObjectId(id) });
                res.render("admin/public/success.html", {
                    "redirectUrl": `/${config.adminPath}/articleCate`,
                    "message": "删除数据成功"
                });
            }
        }
    } catch (error) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${config.adminPath}/articleCate`,
            "message": "修改数据失败"
        });
    }
});

module.exports = router